// src/services/speechService.js

import { ref } from 'vue';

const isSpeaking = ref(false);
const utterance = ref(null);
const voices = ref([]); // 存储可用语音
const selectedVoiceURI = ref(localStorage.getItem('selectedVoiceURI') || null); // 存储用户选择

// 【新增】语速和音调的状态，并从 localStorage 初始化
const speechRate = ref(parseFloat(localStorage.getItem('speechRate') || '1'));
const speechPitch = ref(parseFloat(localStorage.getItem('speechPitch') || '1'));

/**
 * 核心函数：更新语音列表
 * 这个函数会被浏览器在语音加载完成后自动调用
 */
const updateVoiceList = () => {
  const allVoices = window.speechSynthesis.getVoices();
  if (allVoices.length === 0) {
    return; // 如果列表为空，则不作处理
  }

  // 筛选出所有中文语音包
  voices.value = allVoices.filter(voice => voice.lang.startsWith('zh-'));

  // 如果用户还没有选择过语音，并且列表不为空，则自动选择第一个作为默认语音
  const hasSelection = voices.value.some(v => v.voiceURI === selectedVoiceURI.value);
  if (!hasSelection && voices.value.length > 0) {
    const defaultVoice = voices.value[0];
    selectedVoiceURI.value = defaultVoice.voiceURI;
    localStorage.setItem('selectedVoiceURI', defaultVoice.voiceURI);
  }
};

// 【关键修复】
// 1. 立即将 updateVoiceList 函数绑定到 onvoiceschanged 事件。
//    这样，无论何时语音列表发生变化（例如，浏览器加载完成时），我们的列表都会自动更新。
window.speechSynthesis.onvoiceschanged = updateVoiceList;

// 2. 手动调用一次，以处理某些浏览器（如Chrome）不会在初次加载时触发事件，
//    但列表可能已经可用的情况。
updateVoiceList();


const speechService = {
  isSpeaking: isSpeaking,
  availableVoices: voices, // 直接暴露响应式的语音列表
  // 【新增】暴露语速和音调的 ref
  speechRate: speechRate,
  speechPitch: speechPitch,

  getSelectedVoiceURI() {
    return selectedVoiceURI.value;
  },

  setSelectedVoice(voiceURI) {
    const voice = voices.value.find(v => v.voiceURI === voiceURI);
    if (voice) {
      selectedVoiceURI.value = voice.voiceURI;
      localStorage.setItem('selectedVoiceURI', voice.voiceURI);
    }
  },

  // 【新增】设置语速的方法
  setRate(rate) {
    speechRate.value = rate;
    localStorage.setItem('speechRate', rate);
  },

  // 【新增】设置音调的方法
  setPitch(pitch) {
    speechPitch.value = pitch;
    localStorage.setItem('speechPitch', pitch);
  },

  toggleSpeech(textToRead) {
    if (isSpeaking.value) {
      this.stop();
      return;
    }

    if (!textToRead || !textToRead.trim()) {
      console.warn("Speech service: No text provided to read.");
      return;
    }

    const newUtterance = new SpeechSynthesisUtterance(textToRead);

    // 设置用户选择的语音
    const selected = voices.value.find(v => v.voiceURI === selectedVoiceURI.value);
    if (selected) {
      newUtterance.voice = selected;
    }

    newUtterance.lang = 'zh-CN';
    // 【修改】使用响应式状态来设置语速和音调
    newUtterance.rate = speechRate.value;
    newUtterance.pitch = speechPitch.value;

    newUtterance.onend = () => {
      isSpeaking.value = false;
      utterance.value = null;
    };

    utterance.value = newUtterance;
    window.speechSynthesis.speak(utterance.value);
    isSpeaking.value = true;
  },

  stop() {
    if (isSpeaking.value) {
      window.speechSynthesis.cancel();
      // onend 事件不会在 cancel() 后触发，需要手动重置状态
      isSpeaking.value = false;
      utterance.value = null;
    }
  },
};

export default speechService;